package com.cdgeekcamp.redas.wechat.service;

import com.cdgeekcamp.redas.wechat.entity.MessageBaseEntity;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * xml处理
 */
public class XmlProcess {
    public Map<String, String> toMap(String xmlStr) {
        Map<String, String> map = new HashMap<>();

        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new StringReader(xmlStr));
            Element element = document.getRootElement();

            List<Element> elementList = element.elements();
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 将返回的消息对象转成xml
     * @param messageBaseEntity
     * @return
     */
    public String ToXml(MessageBaseEntity messageBaseEntity) {
        XStream xstream = new XStream();
        xstream.alias("xml", messageBaseEntity.getClass());

        return xstream.toXML(messageBaseEntity);
    }
}
